// import {evalStr} from "@/zform/evalGlo";

/**
 *
 * @type {{data(): {reqOptions: []}, created(): Promise<void>, methods: {onRequest(*): Promise<void>}}}
 */
export let baseSelectMixin = {
  data() {
    return {
      reqOptions: []
    }
  },
  inject: ['ZFormProviderIns'],
  methods: {
    async reloadDataSource() {
      let self = this;
      // let lazyLoad = ZY.lodash.get(this.ui, 'widgetConfig.lazyLoad')
      // console.log(this.zfield__highConfig)
     return new Promise(resolve => {
       self.zfield__initDataSource({
         async onRequest(apiConfig, opt) {
           let options = await self.onRequest(apiConfig, opt);
           resolve(options)
         },
         lazyLoad: false
       }, )
     })
    },

    async initDataSource() {
      let self = this;
      let lazyLoad = ZY.lodash.get(this.ui, 'widgetConfig.lazyLoad')

      await this.zfield__initDataSource({
        onRequest(apiConfig, opt) {
          self.onRequest(apiConfig, opt)
        },
        lazyLoad
      }, )
    },
    async onRequest(apiConfig, opt) {
      let zFormMeta = {}
      if (globalThis.ZForm) {
        zFormMeta = globalThis.ZForm.getZFormMeta(this)
      }
      if (this.ZFormProviderIns) {
        zFormMeta = this.ZFormProviderIns.getMeta()
      }
      this.reqOptions  = await this.zfield__req(zFormMeta,{
        event: 'fetch',
        options: {
          apiConfig,
          ...opt
        }
      });
      // console.log( this.reqOptions)
      return this.reqOptions
    },
  }
}

/**
 * 提供watches属性解析
 * @param props
 * @returns {{data(): {watchId: *}, methods: {installWatchUpdate(): void, unInstallWatchUpdate(): void}}|{watchId: *}}
 */
export function createWatchMixin(propConfig = {}, props = {})  {
  return {
    data() {
      return {
        watchId: ZY.rid(),
        watchesArr: [],
        watchesFields: {}
      }
    },
    methods: {
      async installWatchUpdate() {
        let watchesStr = ZY.lodash.get(propConfig, 'server.watches')
        // console.log(propConfig, watchesStr)
        if (watchesStr) {
          try {
            let o = ZY.JSON5.parse(watchesStr);
            // console.log(o)
            let arr = o.events ?? []
            // console.log( this.watchesArr)

            this.watchesArr = arr.map(v => {
              let action = ZY.JSON5.parse(ZY.JSON5.parse(v.action));
              v.watchAction = action.textContent
              let field = ZY.JSON5.parse(ZY.JSON5.parse(v.field));
              v.watchField = field.textContent;
              if (v.watchField) {
                let a = ZY.JSON5.parse(v.watchField);
                if (a) {
                  let s_path =  ZY.getObjPathFromPathArr(a);
                  this.watchesFields[s_path] = {
                    arr: a,
                    action: v.watchAction
                  }
                }
              }

              return v
            })

          } catch (e) {
            console.log(e)
          }
        }

        if (this.curFormCon && this.curFormCon.registerHook) {
          this.curFormCon.registerHook('afterUpdate', this.watchId, this.private__onModelUpdate)
        }
        if (Array.isArray( this.watchesArr) &&  this.watchesArr.length > 0) {
          return false
        }
        return true

      },
      unInstallWatchUpdate() {
        this.curFormCon.unRegisterHook('afterUpdate', this.watchId)
      },
      private__onModelUpdate ({partName, model, s_path, getCmFieldContext, cmFields, e, ctx}) {
        // console.log(partName, model, s_path, getCmFieldContext, cmFields, e)
        let cur_s_path = ZY.getObjPathFromPathArr(props.pathArr);
        if (cur_s_path === s_path) {
        //
        } else {
          let context = getCmFieldContext(cur_s_path);
          // let watchesArr = context.watchesArr

          // console.log(context, cur_s_path)

          // TODO BUG
          // if(context && context.watchesFields && context.watchesFields[s_path]) {
          //   // console.log(context.watchesFields[s_path]);
          //   let cur = context.watchesFields[s_path];
          //   if (cur) {
          //     let ret = evalStr(cur.action, {
          //       async RELOAD_SOURSE() {
          //         // console.log(1)
          //         await context.initDataSource()
          //       }
          //     })
          //   }
          // }
          // console.log(cur_s_path, partName, model, s_path, getCmFieldContext, cmFields, e)
        }
      },
    }
  }
}
